import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken, setUser, removeUser } from '@/utils/auth'
import { TokenKey, UserKey } from '@/utils/request'

const state = {
  token: getToken(),
  userInfo: JSON.parse(localStorage.getItem(UserKey) || 'null')
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_USER_INFO: (state, userInfo) => {
    state.userInfo = userInfo
  }
}

const actions = {
  // 登录
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password })
        .then(response => {
          const { data } = response
          if (data.token) {
            commit('SET_TOKEN', data.token)
            commit('SET_USER_INFO', data)
            setToken(data.token)
            setUser(data)
            resolve(data)
          } else {
            reject(new Error('登录失败：未获取到token'))
          }
        })
        .catch(error => {
          console.error('Login error in store:', error)
          reject(error)
        })
    })
  },

  // 获取用户信息
  getInfo({ commit }) {
    return new Promise((resolve, reject) => {
      getInfo()
        .then(response => {
          const { data } = response
          if (!data) {
            reject(new Error('获取用户信息失败，请重新登录'))
            return
          }
          commit('SET_USER_INFO', data)
          setUser(data)
          resolve(data)
        })
        .catch(error => {
          reject(error)
        })
    })
  },

  // 登出
  logout({ commit }) {
    return new Promise((resolve, reject) => {
      try {
        commit('SET_TOKEN', '')
        commit('SET_USER_INFO', null)
        removeToken()
        removeUser()
        resolve()
      } catch (error) {
        reject(error)
      }
    })
  },

  // 重置token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_USER_INFO', null)
      removeToken()
      removeUser()
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
} 